﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Drawing;
using System.Web.SessionState;
using System.Text;

namespace Cms.Web.Tools
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Files : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            string param = EntLib.Request.GetString("param");
            switch (param) { 
                case "getrandomcode":
                    string random = GetRandomCode(4);
                    HttpContext.Current.Session["login_randomcode"] = random;
                    CreateImage(random);
                    break;
                case "collect":
                    string url=EntLib.Request.GetString("url");
                    int ruleid=EntLib.Request.GetInt("ruleid",0);
                    CollectContent(url, ruleid);
                    break;
                default:
                    break;
            }
        }
        void ResponseText(string text)
        {
            HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
            HttpContext.Current.Response.Expires = -1;
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(text);
            HttpContext.Current.Response.End();
        }
        void ResponseStream(byte[] ms)
        {
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.CacheControl = "no-cache";
            HttpContext.Current.Response.AppendHeader("Pragma", "No-Cache");
            HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
            HttpContext.Current.Response.Expires = -1;
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "image/Jpeg";
            HttpContext.Current.Response.BinaryWrite(ms);
            //Response.Write(ms);
            HttpContext.Current.Response.End();
        }
        private string CollectContent(string Url,int RuleId) {
            String Result = "";
            BLL.BaseDao<Model.Rssrules,int> bll=new BLL.BaseDao<Model.Rssrules,int>();
            Model.Rssrules Rssrule = bll.GetById(RuleId,false);
            if (Rssrule == null) {
                List<Model.Rssrules> list = bll.GetAll();
                if(list.Count>0)
                Rssrule = list[0];
                //Rssrule = list.Find(delegate(Model.Rssrules m) { return m.Siteid });
            }
            if (Rssrule != null) { 
                EntLib.WebDataCollect webdata = new EntLib.WebDataCollect();
                webdata.Url = Url;
                Dictionary<string, string> dictRule = new Dictionary<string, string>();
                Dictionary<string, string> dictDbfield = new Dictionary<string, string>();
                foreach (Model.Rssruledetail detail in Rssrule.Rules) {
                    dictRule.Add(detail.Title, detail.Rule);
                    dictDbfield.Add(detail.Title, detail.Dbfield);
                }
                Dictionary<string, string> dictContent=webdata.ParseData(dictRule);
                string[] keys=new string[dictDbfield.Keys.Count];
                dictDbfield.Keys.CopyTo(keys, 0);
                foreach (string key in keys ) {
                    if (!dictContent.ContainsKey(key))
                        dictDbfield.Remove(key);
                }
                StringBuilder sbSql = new StringBuilder();
                string[] fields = new string[dictDbfield.Count];
                dictDbfield.Values.CopyTo(fields,0);
                sbSql.AppendFormat(" insert into {0}(ID,{1})",Rssrule.TableName,string.Join(",",fields));
                sbSql.AppendFormat(" values('{0}',@{1})",System.Guid.NewGuid().ToString(),string.Join(",@",fields));
                List<Cms.BLL.ParamInfo> paramInfos = new List<BLL.ParamInfo>();
                foreach (KeyValuePair<string, string> field in dictDbfield) { 
                    object obj=null;
                    if(dictContent.ContainsKey(field.Key)){
                        obj=dictContent[field.Key];
                    }
                    paramInfos.Add(new BLL.ParamInfo(field.Value, obj, System.Data.DbType.String));
                }
               int count= BLL.BaseDao<Model.Rssrules, int>.ExecuteSQL(sbSql.ToString(), paramInfos.ToArray());
               Result = count > 0 ? "true" : "false";
            }
            return Result;
        }
        private string GetRandomCode(int length) {
            string guid = System.Guid.NewGuid().ToString().Replace("-","");
            Random rd = new Random();
            int pos=rd.Next(guid.Length - length);
            return guid.Substring(pos, length);
        }
        private void CreateImage(string checkCode)
        {
            int iwidth = (int)(checkCode.Length * 14);
            using (System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20))
            {
                using (Graphics g = Graphics.FromImage(image))
                {
                    Font f = new System.Drawing.Font("新宋体 ", 10);//, System.Drawing.FontStyle.Bold);
                    Brush b = new System.Drawing.SolidBrush(Color.Black);
                    Brush r = new System.Drawing.SolidBrush(Color.FromArgb(166, 8, 8));

                    g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue), 0, 0, image.Width, image.Height);
                    g.Clear(Color.AliceBlue);//背景色
                    g.Clear(System.Drawing.ColorTranslator.FromHtml("#EDFCFF"));//背景色

                    char[] ch = checkCode.ToCharArray();
                    for (int i = 0; i < ch.Length; i++)
                    {
                        if (ch[i] >= '0' && ch[i] <= '9')
                        {
                            //数字用红色显示
                            g.DrawString(ch[i].ToString(), f, r, 3 + (i * 12), 3);
                        }
                        else
                        {   //字母用黑色显示
                            g.DrawString(ch[i].ToString(), f, b, 3 + (i * 12), 3);
                        }
                    }

                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                    image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    ResponseStream(ms.ToArray());
                    g.Dispose();
                    image.Dispose();
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
